import jwt
from django.contrib.auth import get_user_model
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed, NotAuthenticated
from dj_interview_api_server import settings
# 自定义登录认证类
class JWTAuth(BaseAuthentication):
    # 对父类登录认证方法进行重写
    def authenticate(self, request):
        # 获取请求头
        auth_header=request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            raise NotAuthenticated('没有检测到登录凭证token')
        token=auth_header.split(" ")[1]
        # 对token进行解析
        try:
            payload=jwt.decode(token,settings.SECRET_KEY,algorithms='HS256')
        except jwt.DecodeError:
            raise AuthenticationFailed('登录凭证token解析失败')
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('登录凭证token已过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('非法登录凭证token')
        # 从payload中获取user_id
        user_id=payload.get('user_id')
        # 动态获取用户数据表模型类
        User=get_user_model()
        # 查询用户表获取用户的其他信息
        try:
            user=User.objects.get(pk=user_id)
        except User.DoesNotExist:
            raise AuthenticationFailed('用户信息不存在')
        return user,token